const api = require('../../utils/api');
var app = getApp();

// 商品图片映射
const productImageMap = {
  1: 'https://image.jianke.com/mall/product/202106/3b27b6b1746d41ec963c25a822d0c91c.jpg' ,
  2: 'https://img.yaopinnet.com/img500/202304/ttrp7m1682505827.jpg',
  3: 'https://img.alicdn.com/bao/uploaded/i2/3079557865/O1CN01VPG9Iv27yDvAx5S7H_!!0-item_pic.jpg',
  4:'https://m.360buyimg.com/mobilecms/s750x750_jfs/t1/114892/26/2955/311564/5ea54984E9c7a905e/b9538815efaaf11d.jpg!q80.dpg',
  5:'https://img00.miaoshoucdn.com/product/watermark/2/33/2339bd29f5fb7cbde0517237d37dab25.jpg',
  6:'https://image.jianke.com/mall/product/202403/f9afc318cc2b488daaa7ec601eaadd1f.jpg',
  7:'https://tse4-mm.cn.bing.net/th/id/OIP-C.MZJcYU9GJ2M0HuMsk8RSQQHaHk?cb=iwc1&rs=1&pid=ImgDetMain',
  8:'https://img.alicdn.com/bao/uploaded/O1CN016K9OFP1FWkpsb9Xbr_!!6000000000495-0-yinhe.jpg',
  9:'https://image.jianke.com/upload/prodimage/201603wm/2016314162632378.jpg',
  10:'https://image.jianke.com/upload/prodimage/201604wm/2016420165456455.jpg',
  11:'https://ts1.tc.mm.bing.net/th/id/R-C.282b4e626d6bf64ab21efce5e60ba641?rik=DHFEBNDoGAxCJQ&riu=http%3a%2f%2fupload.qianlong.com%2f2021%2f0804%2f1628068305374.png&ehk=VoRCxDNnFfbRysYq5L8nWdAqC9w4JaXWa3%2fctdwiefE%3d&risl=&pid=ImgRaw&r=0',
  12:'https://cbu01.alicdn.com/img/ibank/O1CN01p1IL4T1mgGOJfl1L3_!!3856244983-0-cib.jpg',
};

// 模拟评价数据
const mockReviews = [
  {
    user: '用户123',
    avatar: 'https://randomuser.me/api/portraits/women/44.jpg',
    content: '药品效果很好，物流也很快，下次还会再来购买！',
    time: '2023-05-15',
    rating: 5
  },
  {
    user: '健康生活',
    avatar: 'https://randomuser.me/api/portraits/men/32.jpg',
    content: '包装很严实，正品保障，价格也实惠。',
    time: '2023-04-28',
    rating: 4
  }
];

Page({
  data: {
    medicine: {
      name: '',
      price: 0,
      description: '',
      imageUrl: ''
    },
    num: 1, // 当前选择的数量
    buycar_num: 0, // 购物车总数量
    totalPrice: 0, // 当前商品的小计金额
    reviews: mockReviews,
    stockStatus: '充足', // 库存状态
    salesVolume: '100+', // 销量
    rating: '4.9' // 评分
  },

  onLoad: function(options) {
    const id = options.id;
    this.loadProductDetails(id);
    this.updateCartInfo();
    
    // 初始化小计金额
    this.calculateTotalPrice();
  },

  loadProductDetails: function(id) {
    api.getMedicines()
      .then((medicines) => {
        const medicine = medicines.find((item) => item.id == id) || {
          id: id,
          name: '商品名称',
          price: 99.00,
          description: '这是商品的详细描述信息，包含功效、使用方法等。'
        };
        
        medicine.imageUrl = productImageMap[id] || '/assets/images/default-product.png';
        
        this.setData({
          medicine: medicine
        }, () => {
          // 商品数据加载完成后重新计算小计金额
          this.calculateTotalPrice();
        });
      })
      .catch((err) => {
        console.error('获取商品详情失败:', err);
        wx.showToast({
          title: '加载商品失败',
          icon: 'none'
        });
      });
  },

  // 计算当前商品的小计金额
  calculateTotalPrice: function() {
    const totalPrice = (this.data.medicine.price * this.data.num).toFixed(2);
    this.setData({
      totalPrice: totalPrice
    });
  },

  updateCartInfo: function() {
    this.setData({
      buycar_num: app.globalData.buycar_num || 0
    });
  },

  reduce: function() {
    if (this.data.num > 1) {
      this.setData({
        num: this.data.num - 1
      }, () => {
        // 数量变化后重新计算小计金额
        this.calculateTotalPrice();
      });
    }
  },

  add: function() {
    this.setData({
      num: this.data.num + 1
    }, () => {
      // 数量变化后重新计算小计金额
      this.calculateTotalPrice();
    });
  },

  goToCart: function() {
    wx.switchTab({
      url: '/pages/cart/cart'
    });
  },

  toSubmitOrder: function() {
    if (this.data.num > 0) {
      const medicine = this.data.medicine;
      
      console.log('传递到结算页的商品数据:', medicine); // 添加日志输出
      wx.navigateTo({
        url: `../submitOrder/submitOrder?medicineId=${medicine.id}&num=${this.data.num}&price=${medicine.price}&name=${encodeURIComponent(medicine.name)}&specification=${encodeURIComponent(medicine.specification || '')}&imageUrl=${encodeURIComponent(medicine.imageUrl || '')}`
      });
    } else {
      wx.showToast({
        title: '请选择购买数量',
        icon: 'none'
      });
    }
  },
  addToCart: function() {
    if (this.data.num > 0) {
      const medicine = this.data.medicine;
      const num = this.data.num;
      const cartList = app.globalData.cartList || [];

      // 检查商品是否已在购物车中
      const existingItemIndex = cartList.findIndex(item => item.id === medicine.id);

      if (existingItemIndex !== -1) {
        // 如果商品已在购物车中，增加数量
        cartList[existingItemIndex].num += num;
      } else {
        // 如果商品不在购物车中，添加新商品
        const newItem = {
          id: medicine.id,
          name: medicine.name,
          price: medicine.price,
          imageUrl: medicine.imageUrl,
          num: num,
          selected: true
        };
        cartList.push(newItem);
      }

      // 更新全局购物车数据
      app.globalData.cartList = cartList;
      app.globalData.buycar_num = (app.globalData.buycar_num || 0) + num;
      app.globalData.totalMoney = (app.globalData.totalMoney || 0) + (medicine.price * num);

      // 更新购物车信息显示
      this.updateCartInfo();

      // 提示添加成功
      wx.showToast({
        title: '添加到购物车成功',
        icon: 'success',
        duration: 1500
      });
    } else {
      wx.showToast({
        title: '请选择购买数量',
        icon: 'none'
      });
    }
  },
});